/**
 * 
 */
package poiTests;

import java.io.*;
import java.util.Iterator;

import junit.framework.TestCase;

import org.junit.Before;
import org.junit.Test;

import POI.GeoInfo;
import POI.GeoInfoList;

/**
 * @author pdudnyt
 *
 */
public class GeoInfoListTest extends TestCase {
	GeoInfoList il;
	
	@Before
    public void setUp() {
		il = new GeoInfoList();
	}
	
	@Test
	public void testLoadFromFile() {
		FileWriter f;
		try {
			f = new FileWriter("__temp_test__.csv");
			f.write("1,Chernivtsi,My,48.3,25.933\n");
			f.write("2,L'viv,Store,49.85,24.0167\n");
			f.write("3,Kyiv,Food,50.45,30.5233\n");
			f.write("4,Suceava,Recreation,47.651389,26.2556");
			f.close();
		} catch (IOException e) {
			fail("Temp test file is not accessible!");
		}
		assertTrue(il.loadFromFile("__temp_test__.csv"));
		assertEquals(4, il.size());
   		Iterator<GeoInfo> it = il.iterator();
		GeoInfo val = it.next();
		assertEquals("1,Chernivtsi,My,48.3,25.933",val.toString());
		val = it.next();
		assertEquals("2,L'viv,Store,49.85,24.0167", val.toString());
		val = it.next();
		assertEquals("3,Kyiv,Food,50.45,30.5233", val.toString());
		val = it.next();
		assertEquals("4,Suceava,Recreation,47.651389,26.2556", val.toString());
		assertTrue(il.loadFromFile("__temp_test__.csv"));
		assertEquals(4, il.size());
		File df = new File("__temp_test__.csv");
		if(!df.delete()) fail("Can't delete temp test file!");
	}

	@Test
	public void testSaveToFile() {
		il.clear();
		il.add(new GeoInfo(1,"Chernivtsi","My",48.3,25.933));
		il.add(new GeoInfo(2,"L'viv","Store",49.85,24.0167));
		il.add(new GeoInfo(3,"Kyiv","Food",50.45,30.5233));
		il.add(new GeoInfo(4,"Suceava","Recreation",47.651389,26.2556));
		assertTrue(il.saveToFile("__temp_test__.csv"));
		assertTrue(il.saveToFile("__temp_test__.csv"));
        BufferedReader in=null;
        String fileContent = new String();
   		Iterator<GeoInfo> it = il.iterator();
		GeoInfo val = it.next();
        int linesCount=0;
        try {
            in = new BufferedReader(new InputStreamReader(new FileInputStream("__temp_test__.csv")));
            while (in.ready()) {
            	fileContent = in.readLine();
            	linesCount++;
            	assertEquals(val.toString(), fileContent);
            	if(in.ready())
            	{
            		assertTrue(it.hasNext());
            	   	val = it.next();
            	}
            }
        } catch (IOException e) {
        	fail("Error reading temp file!");
        }
        finally {
            try {
				in.close();
			} catch (IOException e) {
	        	fail("Error working with temp file!");
			}
            File df = new File("__temp_test__.csv");
    		if(!df.delete()) fail("Can't delete temp test file!");
        }
		assertEquals(4, linesCount);
	}
}
